﻿using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using VisionCloud.Service.Ms;
using VisionCloud.Utility;

namespace VisionCloud.Web.Service
{
    /// <summary>
    /// 定时删除下载、分析的临时压缩包文件
    /// </summary>
    public class SharingFilesDeleteService : BackgroundService
    {
        private StatisService _statisService { get; set; }

        /// <summary>
        /// 时间间隔（天）
        /// </summary>
        private static readonly int timeInterval = ConfigHelper.GetValue<int>("TimeInterval");

        private static readonly string taskReportData = ConfigHelper.GetValue<string>("TaskReportData");

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                #region 删除临时下载文件

                string dirPath = $"/{taskReportData}/download/";
                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    dirPath = dirPath.Remove(0, 1);
                }
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }

                var files = Directory.GetFiles(dirPath, "*.zip");
                if (files?.Length > 0)
                {
                    // 删除7天前分享文件
                    var existed = files.Where(f => DateTime.Now.Subtract(new FileInfo(f).CreationTime).Days >= timeInterval)
                        .ToList();
                    foreach (var item in existed)
                    {
                        File.Delete(item);
                        Logger.Info($"删除下载文件：{item}");
                    }
                }

                #endregion 删除临时下载文件

                // 删除7天前文件
                await Task.Delay(TimeSpan.FromDays(timeInterval), stoppingToken).ConfigureAwait(false);
            }
        }
    }
}